<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购计划 / 采购计划维护 / 历史计划</span>

    <div class="demo-date-picker" style="margin-top: 10px">
      <div class="block">
        <span class="demonstration">请选择统计季度</span>
        <el-date-picker
            v-model="time"
            type="month"
            placeholder="Pick a cycle"
            :shortcuts="shortcuts"
            @change="updateVariable"
        />
      </div>
    </div>

    <div ref="chartRef" style="width: 100%; height: 40vh;"></div>

    <div style="display: flex;justify-content: center">
      <span style="font-weight: bold;font-size: large">采购计划执行详情</span>
    </div>
    <el-table v-loading="loading" :data="purchasePlanList"
              style="margin-top: 25px; height: 80%" t>
      <el-table-column label="计划编号" fixed align="center" prop="planNo"/>
      <el-table-column label="货品编码" align="center" prop="code"/>
      <el-table-column label="货品名称" align="center" prop="rawProductName"/>
      <el-table-column label="预期购买数量(吨)" align="center" prop="quantity"/>
      <el-table-column label="实际购买数量(吨)" align="center" prop="purchaseQuantity"/>
      <el-table-column label="需求日期" align="center" prop="demandDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.demandDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center" prop="modifiedDate" width="180px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="备注" align="center" prop="remarks" width="200px"/>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>

</template>

<script setup name="PurchasePlan">
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import {checkLatestPurchasePlan, getStatisticInfo, listPurchasePlan} from "@/api/purchase/purchasePlan.js";
import {parseTime} from "@/utils/ruoyi.js";
import {ElLoading} from "element-plus";

const { proxy } = getCurrentInstance();

// 准备数据
const data = ref([]);
const showData = ref([])
const dateList = ref([])
const quantity = ref([])
const purchaseQuantity = ref([])
const time = ref([]);
const purchasePlanList = ref([]);
const loading = ref(false);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 5,
  cycleNo:getCurrentDate(),
});

// 创建一个响应式引用，用于存储图表实例
const chartRef = ref(null);
let myChart = null;

const shortcuts = ref([
  {
    text: '本季度',
    value: new Date(),
  },
  {
    text: '上季度',
    value: () => {
      const date = new Date()
      date.setMonth(date.getMonth() - 1)
      return date
    },
  },
  {
    text: '前季度',
    value: () => {
      const date = new Date()
      date.setMonth(date.getMonth() - 2)
      return date
    },
  },
])
// 定义图表配置项
const option = ref({
  visualMap: [
    {
      show: false,
      type: 'continuous',
      seriesIndex: [0,1],
      min: 0,
      max: 400
    }
  ],
  title: [
    {
      left: 'center',
      text: '采购计划执行统计'
    }
  ],
  legend: {
    right: '10%',
    top: '10',
    orient: 'horizontal',
    data: ['计划采购数量', '实际采购数量']
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    data: dateList,
    axisLabel: {
      interval: 0,
      rotate: 35
    }
  },
  yAxis: {
    axisLabel: {
      formatter: '{value} 吨'
    }
  },
  grid: {
    bottom: '18%'
  },
  series: [
    {
      name: '计划采购数量',
      type: 'line',
      showSymbol: false,
      data: quantity,
      lineStyle: {
        color: '#5470C6' // 设置计划采购数量线条的颜色为红色
      }
    },
    {
      name: '实际采购数量',
      type: 'line',
      showSymbol: false,
      data: purchaseQuantity,
      lineStyle: {
        color: '#00FF00' // 设置实际采购数量线条的颜色为绿色
      }
    }
  ]
});

// 在组件挂载后初始化图表
onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    myChart.setOption(option.value);

    getStatisticList();
    getList();
  }
});

// 监听option变化，以动态更新图表
watch(option, () => {
  if (myChart) {
    myChart.setOption(option.value);
  }
}, { deep: true });

// 处理组件卸载，释放图表实例
onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});

/** 监听时间选择并为变量赋值 */
function updateVariable(){
  if(!time.value || time.value.length === 0){
    queryParams.value.cycleNo = getCurrentDate();
  }else{
    const year = time.value.getFullYear().toString();
    const month = (time.value.getMonth() + 1).toString().padStart(2, '0');
    queryParams.value.cycleNo = `${year}${month}`;
  }
  getStatisticList();
  getList();
}

/** 从后端获取表格数据 */
function getList() {
  loading.value = true;
  listPurchasePlan(queryParams.value).then(response => {
    purchasePlanList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 从后端获取统计数据 */
function getStatisticList(){
  getStatisticInfo(queryParams.value.cycleNo).then(response => {
    showData.value = response.data;
    dateList.value = showData.value.map(item => item.rawProductName);
    quantity.value = showData.value.map(item => item.quantity);
    purchaseQuantity.value = showData.value.map(item => item.purchaseQuantity);
  });
}

/** 按钮跳转 */
function handleForecast(){
  checkLatestPurchasePlan().then(response => {
    let num = response.data;
    //当前最新计划已生成
    if(num > 0){
      // proxy.$router.push({
      //   path:'/ForecastShow',
      // });
      proxy.$router.push({
        path:'/DemandForecast',
      });
    }
    //跳转到预测页面 ->调用后端预测代码并配置计划详情
    else{
      const loadingStatus = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loadingStatus.close()
        proxy.$router.push({
          path:'/DemandForecast',
        });
      }, 3000);
    }
  });
}

function getCurrentDate(){
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  return year + month;
}

</script>

<style scoped>
.custom-large-button {
  font-size: 17px; /* 调整字体大小 */
  padding: 15px 30px; /* 增加内边距 */
  height: 40px; /* 设置高度 */
  width: 120px; /* 设置宽度 */
}
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 20px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-right: 10px;
}
</style>